// pages/login/login.js
const API = require('../../utils/api.js')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    type:"",
    username:"",
    password:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      type:options.type
    })
  },

  inputUsername:function(e) {
    this.setData({
      username:e.detail.value
    })
  },

  inputPassword:function(e) {
    this.setData({
      password: e.detail.value
    })
  },

  login:function() {
    let that = this
    if(this.data.username == ""){
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      })
      return
    }
    if(this.data.password == ""){
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '验证中',
    })
    wx.request({
      url: this.getUpdateApi(this.data.type),
      method: 'POST',
      data: {
        'name': that.data.username,
        'password': that.data.password
      },
      success(res){
        wx.hideLoading()
        console.log(res.data)
        if(res.data.code == "FAIL"){
          util.showTips(res.data.message,2000)
          that.setData({
            username:'',
            password:''
          })
        }
        else{
          app.globalData.usertype = that.data.type
          app.globalData.userinfo = res.data.data
          app.globalData.isLogin = true
          wx.setStorageSync('usertype', that.data.type)
          wx.setStorageSync('userinfo', app.globalData.userinfo)
          wx.setStorageSync('isLogin', true)
          wx.navigateBack()
        }
      },
      fail() {
        wx.hideLoading()
        util.showNetworkError()
      },
    })
  },

  gotoRegister:function() {
    wx.navigateTo({
      url: '/pages/register/register?type='+this.data.type,
    })
  },

  getUpdateApi: function (type) {
    if (type == "customer") {
      return API.Customer.login
    } else if (type == "seller") {
      return API.Seller.login
    } else if (type == "producer") {
      return API.Producer.login
    } else if (type == "transporter") {
      return API.Transporter.login
    }
  }
})